﻿using MediatR;
using WorkflowCore.Interface;
using Yuekao.API.Write.Command;
using Yuekao.Domain.API;
using Yuekao.Domain.BaseReposi;
using Yuekao.Domain.dto;
using Yuekao.Domain.Entitys;

namespace Yuekao.API.Write.CommandHander
{
    public class AuditAddCommandHandler : IRequestHandler<AuditAddCommand, APIResult<int>>
    {
        private readonly IBaseRepository<AuditModel> _repository;
        private readonly IWorkflowHost _workflowHost;
        public AuditAddCommandHandler(IBaseRepository<AuditModel> repository, IWorkflowHost workflowHost)
        {
            _repository = repository;
            _workflowHost = workflowHost;
        }
        public async Task<APIResult<int>> Handle(AuditAddCommand request, CancellationToken cancellationToken)
        {
            APIResult<int> result=new APIResult<int>();
            var list = await _repository.GetValues(x=>x.WorkflowId==request.WorkflowId&&x.State==false&&x.AuditId==request.UserId);
            if(list==null)
            {
                result.Code = APIEnum.Fail;
                result.Message = "暂无审批任务";
                return result;
            }

            list.Remark = request.Remark;
            list.AuditType = request.AuditType;
            list.CreateTime=DateTime.Now;
            list.State = true;
            _repository.Update(list);

            AuditInput input = new AuditInput();
            input.WorkflowId = request.WorkflowId;
            input.Remark = request.Remark;
            input.AuditType = request.AuditType;

            await _workflowHost.PublishEvent("MyEvent",request.WorkflowId, input);

            result.Code = APIEnum.Success;
            result.Message = "审批成功";
            result.Data = 1;
            return await Task.FromResult(result);
        }
    }
}
